package 实现数据结构.实现动态数组;

import java.util.Arrays;

/**
 * @DESC 自己实现ArrayList
 * @Author tzq
 * @Date 2019-10-06 16:16
 **/
public class ArrayList<I extends Number> {

    private static final int INITIAL_SIZE = 10;
    private int size = 0;
    private int realSize = 0;
    private int[] array;

    public ArrayList() {
        array = new int[INITIAL_SIZE];
    }

    public ArrayList(int initial) {
        if (initial <= 0) {
            initial = INITIAL_SIZE;
        }
        array = new int[initial];
    }

    // add
    public void add(int num) {
        if (size == array.length) {
            array = Arrays.copyOf(array, size * 2);
            realSize = size * 2;
        }
        array[size++] = num;
    }

    //get 获取指定位置的元素
    public int get(int i) {
        if (i >= size) {
            throw new IndexOutOfBoundsException("获取的元素位置超过最大长度");
        }
        return array[i];
    }

    // set 设置指定位置的元素
    public int set(int i, int num) {
        int old = get(i);
        array[i] = num;
        return old;
    }

    // 获取变长数组的长度
    public int size() {
        return size;
    }

    // 获取变长数组的实际长度
    public int realSize() {
        return realSize;
    }

    public static void main(String[] args) {
        ArrayList<Number> arrayList = new ArrayList<Number>(1);
        arrayList.add(1);
        arrayList.add(2);
        System.out.println("数组长度1：" + arrayList.realSize());
        arrayList.add(3);
        arrayList.add(4);
        System.out.println("数组长度2：" + arrayList.realSize());
        arrayList.add(5);
        System.out.println("数组长度3：" + arrayList.realSize());

        System.out.println("下标为3的元素：" + arrayList.get(3));


        arrayList.set(3, 9);

        System.out.println("下标为3的元素：" + arrayList.get(3));
        System.out.println("数组实际长度：" + arrayList.realSize());


    }

}
